import React, {Component, PureComponent} from 'react';
import {
    View, Text, FlatList, ListView,
    StyleSheet,
    Dimensions
} from 'react-native';

import ListItem from './ListItem';
import cleanTitle from '../utils/TitleCleaner';

const {width: screenWidth} = Dimensions.get('window');

export default class AlimamaListView extends PureComponent {
    urlBase = `http://pub.alimama.com/items/search.json?perPageSize=20&q=女装`;
    ds = new ListView.DataSource({
        rowHasChanged: (r1, r2) => r1 != r2,
    });
    state = {
        ds: this.ds,
    }
    items = [];
    currentPage = 0;
    _renderItem = (item) => {
        const itemWrapper = {
            title: item.title,
            imgUrl: 'http:' + item.pictUrl,
        };
        return <ListItem style={styles.item} item={itemWrapper} itemWidth={screenWidth / 2 - 10}/>
        // return <Text style={styles.item}>text:longlonglonglonglonglonglonglonglonglonglonglonglonglong</Text>
        // return (
        //     <View style={styles.item}>
        //         <Text>text: longlonglonglonglonglonglonglonglonglonglonglonglonglong</Text>
        //     </View>
        // )
    };
    _keyExtractor = (item, index) => item.auctionId.toString() + index;
    _getItemLayout = (data, index) => {
        return {
            length: 120,
            offset: Math.floor(index / 2) * 120,
            index,
        }
    };
    _fetchItems = async () => {
        let url = `${this.urlBase}&toPage=${this.currentPage}`
        console.log(`fetching page: ${this.currentPage}`);
        let data = await this._doFetch(url);
        if (data === null) {
            console.log('No data');
        }
        else {
            console.log(`Fetched ${data.length} items`);
            data = data.map(item => {
                item.title = cleanTitle(item.title);
                return item;
            })
            this.items = [...this.items, ...data]
            this.setState({
                ds: this.state.ds.cloneWithRows(this.items),
            });
            this.currentPage += 1;
        }
    };
    _doFetch = (url) => {
        return fetch(url).then(resp => resp.text()).then(textResp => {
            const json = JSON.parse(textResp);
            return json;
        }).then(jsonResp => jsonResp.data.pageList).catch(err => {
            console.log('Fetching data failed', err);
            return null;
        })
    }

    componentWillMount () {
        this._fetchItems();
    };
    render() {
        return (
            <View>
                <Text>Hello, world</Text>
                <ListView
                    contentContainerStyle={styles.list}
                    dataSource={this.state.ds}
                    renderRow={this._renderItem}
                    onEndReached={this._fetchItems}
                    onEndReachedThreshold={30}
                    // numColumns={2}
                    // getItemLayout={this._getItemLayout}
                    removeClippedSubviews={true}
                    initialListSize={20}
                />
            </View>
        );
    }
}

const styles = StyleSheet.create({
    list: {
        // flex: 1,
        flexDirection: 'row',
        flexWrap: 'wrap',
    },
    item: {
        // flex: 1,
        width: screenWidth / 2 - 10,
        margin: 3,
    },
});